package com.demo;

import com.demo.event.MyUserEvent;
import com.demo.event.User;
import com.demo.listener.MyApplicationEnvironmentPreparedListener;
import com.demo.listener.MyGenericApplicationListener;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class C1Application {
    public static void main(String[] args) throws InterruptedException {
        SpringApplication application=new SpringApplication(C1Application.class);
        //此处的监听会被添加到EventPublishingRunListener的事件发布器中，也可以直接将要添加的监听器注册为bean，就可以不用通过addListeners方法进行添加了
        application.addListeners(new MyApplicationEnvironmentPreparedListener(),new MyGenericApplicationListener());
        ApplicationContext context=application.run(args);
        //此处通过ApplicationContext中事件发布器发布的事件能被上面的MyGenericApplicationListener监听到
        //原因可查看springboot内嵌初始化#2.7.10.1（https://www.processon.com/view/link/5d63a33ee4b04e664f325277）
        context.publishEvent(new MyUserEvent(new User("luobiao")));
        System.out.println("MyUserEvent事件发布结束");

        Thread.sleep(100000     );
        //通过SpringApplicationBuilder添加监听器
        //new SpringApplicationBuilder(Application.class).listeners(new MyApplicationEnvironmentPreparedListener(),new MyGenericApplicationListener()).run(args);
    }
    @Bean
    public ApplicationRunner runner(){
        return (r)->{
            System.out.println(r);
        };
    }
}
